<script setup lang='ts'>
  import { nextTick, reactive, ref } from 'vue';
  import { propApi } from '@/api/controller';
  import { ToastError, ToastSuccess, ToastWarning, Toastloading, allNumber } from '@/utils/public';
import { ElMessageBox } from 'element-plus';
  const dataForm = ref()
  const $emit = defineEmits(['updateList'])
  const formLabelWidth = 120
  const action = reactive({
    dialogTableVisible:false,
    dialogFormVisible:false,
    disabled:false,
    title:'',
    consumeNum:0,
    awardsNum:0,
    pool_list:[] as Array<poolQuery>,
    pool_id:0,
  })
  interface formQuert {
    id:number
    diamond_num:number
    data_num:number
  }
  let form = reactive({} as formQuert)
  const formRules = {
    data_num: [{ required: true, message: "请输入反奖次数", trigger: "blur" }],
    diamond_num: [{ required: true, message: "请输入返奖钻石数", trigger: "blur" }],
  }
  interface poolQuery {
    id:number
    diamond_num:number
    data_num:number
    gift_price:number
    consume_num:number
    awards_num:number,
  }
  const handleCompute = async()=>{
    let consumeNum = 0
    let awardsNum = 0
    action.pool_list.forEach(res=>{
      const { awards_num=0, consume_num=0 } = res
      consumeNum += consume_num
      awardsNum += awards_num
    })
    action.consumeNum = consumeNum
    action.awardsNum = awardsNum
  }
  const handleForm = (row:any = {})=>{
    action.dialogFormVisible = true
    const { id=0, data_num=0, diamond_num=0  } = row
    if(id) {
      Object.assign(form,{
        id, data_num, diamond_num
      })
    }
  }
  const handleSubmit = ()=>{
    dataForm.value.validate(async(valid:any)=>{
      if(!valid) return
      const { id, data_num=0, diamond_num=0 } = form
      if(!data_num) return ToastError('请输入反奖次数')
      // if(!diamond_num) return ToastError('请输入返奖钻石数')
      const loading = Toastloading()
      let submitSet = false
      if(id) {
        await propApi.luckGiftEditPoolConfig(form).then(()=>{
          ToastSuccess('编辑礼物池成功')
          submitSet = true
        }).catch(()=>{
          loading.close()
        })
      }else {
        await propApi.luckGiftAddPoolConfig({
          pool_id:action.pool_id,
          ...form,
        }).then(()=>{
          ToastSuccess('新增礼物池成功')
          submitSet = true
        }).catch(()=>{
          loading.close()
        })
      }
      if(submitSet) {
        loading.close()
        getPoolList()
        closeDialog()
      }
    })
  }
  const handleDel = (row:any = {})=>{
    const { id=0 } = row
    ElMessageBox.confirm(`确定删除礼物池ID：${id}的配置吗?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      const loading = Toastloading();
      await propApi.luckGiftDelPoolConfig({
        id,
      });
      loading.close();
      ToastSuccess('删除成功');
      getPoolList();
    })
    .catch(() => {});
  }
  const closeDialog = ()=>{
    form = reactive({} as formQuert)
    nextTick(() => {
      dataForm.value.clearValidate();
    });
    action.dialogFormVisible = false
  }
  const getPoolList = async()=>{
    const loading = Toastloading()
    const res = await propApi.luckGiftPoolConfigList({
      pool_id:action.pool_id
    })
    loading.close()
    const { data=[] } = res
    if(!Array.isArray(data)) return action.pool_list = []
    action.pool_list = data.map((res:poolQuery)=>{
      const { data_num=0, diamond_num=0 , gift_price=0} = res
      return {
        ...res,
        // awards_num:data_num * 9,
        awards_num:data_num * (gift_price*0.99),
        consume_num:diamond_num * data_num,
      }
    })
    handleCompute()
  }
  const openDialog = async(query:any={})=> {
    const { id, pool_name='' } = query
    action.pool_id = id
    action.title = `礼物池：${pool_name}-礼物池配置`
    await getPoolList()
    action.dialogTableVisible = true
  }
  defineExpose({
    openDialog
  })
</script>

<template>
  <div>
    <el-dialog
      top="5vh"
      class="xm-dialog"
      v-model="action.dialogTableVisible"
      :close-on-click-modal="action.disabled"
      :close-on-press-escape="action.disabled"
      width="60%"
      :title="action.title">
      <div class="xm-headTab">
        <div class="labelBox">
          <div class="labelItem">
            <el-button type="primary" @click="handleForm()">新增反奖概率</el-button>
            <el-button type="primary" @click="handleCompute">计算概率</el-button>
            <el-button type="primary" @click="getPoolList">刷新</el-button>
          </div>
        </div>
        <div class="labelBox input-width">
          <div class="labelItem">
            <div class="label">礼物池流入：</div>
            <div class="lable-val">{{ action.awardsNum }}钻石</div>
          </div>
          <div class="labelItem">
            <div class="label">礼物池流出：</div>
            <div class="lable-val">{{ action.consumeNum }}钻石</div>
          </div>
          <div class="labelItem">
            <div class="label">回馈率：</div>
            <div class="lable-val">{{ (( action.consumeNum / action.awardsNum) || 0).toFixed(2)*100 }}%</div>
          </div>
        </div>
      </div>
      <el-table
        class="xm-TableCenter"
        :data="action.pool_list"
        height="500"
        border
      >
        <el-table-column width="80" prop="id" label="礼物池ID" />
        <el-table-column min-width="120" prop="diamond_num" label="返奖数(钻石)" />
        <el-table-column min-width="120" prop="data_num" label="返奖次数" />
        <el-table-column min-width="120" prop="awards_num" label="礼物池流入(钻石)" />
        <el-table-column min-width="120" prop="consume_num" label="礼物池流出(钻石)" />
        <el-table-column width="200" label="操作">
          <template #default="scoped">
            <el-button type="primary" @click="handleForm(scoped.row)">编辑礼物池</el-button>
            <el-button type="danger" @click="handleDel(scoped.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      top="10vh"
      class="xm-dialog input-width"
      v-model="action.dialogFormVisible"
      :close-on-click-modal="action.disabled"
      :show-close="action.disabled"
      :close-on-press-escape="action.disabled"
      width="40%"
      :title="action.title">
      <el-form ref="dataForm" :model="form" :rules="formRules">
        <el-form-item :label-width="formLabelWidth" prop="diamond_num" label="返奖钻石数">
          <el-input @input="allNumber(form,'diamond_num')" v-model="form.diamond_num" placeholder="请输入返奖钻石数" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" prop="data_num" label="反奖次数">
          <el-input @input="allNumber(form,'data_num')" v-model="form.data_num" placeholder="请输入反奖次数" />
        </el-form-item>
      </el-form>
      <template v-if="!action.disabled" #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
